<?php


namespace app\api\controller;


use app\common\model\Advert;
use app\common\model\CardLevel;
use app\common\model\Category;
use app\common\model\Goods as Goodsmodel;
use app\common\model\GoodsList;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\Shang;
use app\Request;
use think\facade\Db;
use app\common\model\Danye;
class CardGoods extends Base
{
    
    
    
    
    /**
     * 抽卡及开启关闭
     * @return \think\response\Json
     *created by Admin at 2023/1/3 10:02
     */
    public function open_card(){
        $data = [];
        $info = getConfig('base');
        $data['open_card'] = $info['open_card'];
        return $this->renderSuccess("请求成功", compact('data'));
    }
    /**
     * 抽卡机轮播图和弹幕
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/8 9:13
     */
    public function card_index(){
        //轮播图
        $banner = Db::name('advert')->field('imgurl')
            ->where(['type' => 2])
            ->order('sort desc,id desc')
            ->select();
        foreach ($banner as &$value) {
            $value['imgurl'] = imageUrl($value['imgurl']);
        }
        //查询弹幕
        $bullet_chat= [];
        $order_info =  OrderList::field('id,user_id,goods_id,goodslist_title as title')
            ->append(['user_info','goods_info'])
            ->where('order_type', '=', 4)
            ->order('id desc')
            ->limit(20)
            ->select();
//        dd($order_info);
        foreach ($order_info as $value) {

            $bullet_chat[] = [
                'headimg' => $value['user_info']['headimg'],
                'content' => $value['user_info']['nickname'] . ' 抽中了 [' . $value['goods_info']['goods_title'] . '] 中的 ' . $value['title'],
            ];
        }
        $data = array();
        $data['advert'] = $banner;
        $data['bullet_chat'] = $bullet_chat;
        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 抽卡机分类列表
     *created by Admin at 2022/12/8 9:08
     */
    public function card_category_list(){
        $data = Category::field('id,title')
            ->order('sort desc,id asc')
            ->select()
            ->toArray();
        array_unshift($data, ['id' => 0, 'title' => '全部IP']);
        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 抽卡机列表
     * @param Request $request
     *created by Admin at 2022/12/8 10:03
     */
    public function card_goods_list(Request $request){
        $category_id = $request->param('type');
        $keyword = request()->param('keyword', '');
        $where = [];
        if ($category_id && $category_id > 0){
            $where[] = ['category_id' ,'=',$category_id];
        }
        if ($keyword){
            $where[] = ['title', 'like', '%' . $keyword . '%'];
        }
        $where[] = ['type','=',4];
        $where[] = ['status','=',1];
        $card_goods = GoodsModel::field("id,title,imgurl,price,show_price,type,stock,sale_stock,status")
            ->where($where)
            ->order('sort desc id desc')
            ->paginate(15);

        foreach ($card_goods as $value){
            $value['imgurl'] = imageUrl($value['imgurl']);
        }
        return $this->renderSuccess('请求成功', $card_goods);
    }

    /**
     * 抽卡机商品详情
     * @param Request $request
     *created by Admin at 2022/12/8 10:16
     */
    public function card_goods_detail(Request $request){

        $goods_id = $request->param('goods_id');
        if (!$goods_id){
            return $this->renderError("参数错误");
        }
        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime')
            ->where(['id' => $goods_id])
            ->where(['status' => 1])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在或已下架");
        }
        
       //查询抽卡规则
        $card_set = getConfig('card_set');
        $right_shang_name = CardLevel::where('id',$card_set['right_shang_id'])->value('title');
        $card_set['right_shang_name'] = $right_shang_name;
        $center_shang_name = CardLevel::where('id',$card_set['center_shang_id'])->value('title');
        $card_set['center_shang_name'] = $center_shang_name;
        $card_goods['card_set'] = $card_set;
        return $this->renderSuccess('请求成功', $card_goods);
        return $this->renderSuccess('请求成功', $card_goods);
    }

    /**
     * 卡等级
     *created by Admin at 2022/12/8 11:07
     */
    public function card_level(){
        $data = CardLevel::field('id,imgurl,title')->select();
        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 盒子商品图鉴
     * @param Request $request
     *created by Admin at 2022/12/8 11:09
     */
    public function shang_goods(Request $request){
        $card_id = $request->param('card_id');
        $shang_id = $request->param('shang_id');
        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime')
            ->where(['id' => $card_id])
            ->where(['status' => 1])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在或已下架");
        }
        //卡等级
        $card_level = CardLevel::field('id,imgurl,title')->select();
        $where = [];
        if ($shang_id){
            $where[] = ['shang_id','=',$shang_id];
        }
        $goods = GoodsList::field('title,imgurl,shang_id,price,real_pro')
            ->where('goods_id',$card_goods['id'])
            ->where($where)
            ->paginate(20);
        foreach ($goods as $value){
            $value['shang_name'] = CardLevel::where('id',$value['shang_id'])->value('title');
        }
        foreach ($card_level as $value){
            $real_pro = GoodsList::field('title,imgurl,shang_id,price,real_pro')
                 ->where('goods_id',$card_goods['id'])
                 ->where('shang_id',$value['id'])
                 ->sum('real_pro');
            $num = GoodsList::field('title,imgurl,shang_id,price,real_pro')
                ->where('goods_id',$card_goods['id'])
                ->where('shang_id',$value['id'])
                ->count();
            if ($num > 0 && $real_pro > 0){
                $value['rate'] = $real_pro / $num / 1000;
            }else{
                $value['rate'] = 0;
            }
        }
        $data['goods'] = $goods;
        $data['card_level'] = $card_level;
        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 抽卡机卡册
     *created by Admin at 2022/12/8 14:12
     */
    public function card_book(Request $request){
        $user = $this->getUser();
        $card_id = $request->param('card_id');
        $title = $request->param('title');
        $type = $request->param('type');
        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime')
            ->where(['id' => $card_id])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在");
        }
        //查询总册数
        $card_goods['count'] = GoodsList::where('goods_id',$card_goods['id'])->count();
        //我拥有的册数
        $card_goods['hove_count']  = OrderList::where('goods_id',$card_goods['id'])
            ->where('user_id',$user['id'])
            ->group('goodslist_id')
            ->count();
        $card_goods['gailv'] = ($card_goods['hove_count'] / $card_goods['count']) * 100;
        //查询我拥有的卡id
        $have_ka_id = OrderList::field('goodslist_id')->where('goods_id',$card_goods['id'])
            ->where('user_id',$user['id'])
            ->where('status', '=', 0)
            ->group('goodslist_id')
            ->column('goodslist_id');
        $have_ka_id =  array_values($have_ka_id);

        $obj = GoodsList::field('goods_id,title,price,real_pro,id,imgurl,prize_code')->where('goods_id',$card_goods['id']);
        if ($type == 1){
            $obj->whereIn('id',$have_ka_id);
        }else if($type == 2){
            $obj->whereNotIn('id',$have_ka_id);
        }
        if ($title){
            $obj->where('title', 'like', '%' . $title . '%');
        }
        $goods_list = $obj->order('sort desc id desc')->paginate(20);
        foreach ($goods_list as $value){
            $num = OrderList::where('goodslist_id',$value->id)
                ->where('user_id',$user['id'])
                ->where('status', '=', 0)
                ->count();
            $value['num'] = $num; 
        }
        
         $data['goods_list'] = $goods_list;
        $data['card_goods'] = $card_goods;
        $config = getConfig("base");
        $yufei = [
            'free_post' => $config['card_free_post'],
            'post_money' => $config['card_post_money'],
        ];
        $data['yuefei'] = $yufei;
        return $this->renderSuccess('请求成功', $data);
    }

    /**
     * 中赏记录
     * @param Request $request
     * created by Admin at 2022/12/8 15:25
     */
    public function card_reward_log(Request $request){

        $card_id = $request->param('card_id');
        $category_id = $request->param('category_id');
        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime')
            ->where(['id' => $card_id])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在");
        }
        $where = [];
        if ($category_id){
            $where[]= ['shang_id','=',$category_id];
        }
        $where[]= ['order_type', '=', $card_goods['type']];
        $info = OrderList::field('user_id,goodslist_title,goodslist_imgurl,shang_id,addtime,count(`id`) as prize_num')
            ->where('goods_id',$card_id)
            ->append(['shang_title', 'user_info'])
            ->where($where)
            ->group("order_id,goodslist_id")
            ->order('id desc')
            ->paginate(20);
        foreach ($info as $value){
            $value['nickname'] = $value['user_info']['nickname'];
            $value['headimg'] = $value['user_info']['headimg'];
            $value['addtime'] = date('Y-m-d H:i:s', $value['addtime']);
            $value['goodslist_imgurl'] = imageUrl($value['goodslist_imgurl']);
        }
        return $this->renderSuccess('请求成功', $info);
    }
    /**
     * 计算金额
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/19 16:19
     */
    public function buy_money(Request $request){
        $user = $this->getUser();
        $card_id = $request->param('card_id'); //盒子id
        $type = $request->param('type', ''); // 抽几发
        $use_money_is = $request->param('use_money_is', 0);       #余额抵扣0不抵扣 1抵扣
        $use_integral_is = $request->param('use_integral_is', 0); #积分抵扣0不抵扣 1抵扣

        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime,card_num')
            ->where(['id' => $card_id])
            ->where(['status' => 1])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在或已下架");
        }
        if ($type != 'left_count' && $type != 'center_count' && $type != 'right_count') {
            return $this->renderError("请求参数错误");
        }
        //奖品信息
        $is_goodslist = GoodsList::field('id')
            ->where('goods_id', '=', $card_goods['id'])
            ->where('num', '=', 0)
            ->where('real_pro', '>', 0)
            ->where('special_stock', '<>', 0)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        //抽数设置
        $card_set = getConfig('card_set');
        if (!isset($card_set[$type])) {
            return $this->renderError("配置错误,请联系管理员");
        }

        $prize_num = $card_set[$type] * $card_goods['card_num'];
        //盒子单价
        $box_price = $card_goods['price'];
        #订单金额 微信支付金额
        $order_total = $order_zhe_total = $price = bcmul("$box_price", "$prize_num", 2);

        #潮币抵扣
        $use_integral = 0;
        if ($use_integral_is == 1) {
            if ($user['integral'] >= $price) {
                $use_integral = $price;
                $price = 0;
            } else {
                $use_integral = $user['integral'];
                $price = bcsub("$price", "{$user['integral']}", 2);
            }
        }
        #余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money'];#
                $price = bcsub("$price", "{$user['money']}", 2);
            }
        }
        #抽奖数量
        // dd($card_set[$type]);
        $goods['prize_num'] = $prize_num;
        $goods['first_num'] = $card_set[$type];
        $data = [
            'goods' => $goods,
            'order_total' => $order_total * 1,
            'order_zhe_total' => $order_zhe_total * 1,

            'price' => $price * 1,
            'integral' => $user['integral'] * 1,
            'use_integral' => $use_integral * 1,
            'money' => $user['money'] * 1,
            'use_money' => $use_money * 1,
        ];
        return $this->renderSuccess("请求成功", $data);
    }
    /**
     * 购买盒子
     * @param Request $request
     *created by Admin at 2022/12/9 9:24
     */
    public function card_goods_buy(Request $request){
        $user = $this->getUser();
        $card_id = $request->param('card_id'); //盒子id
        $type = $request->param('type'); // 抽几发
        $use_money_is = $request->param('use_money_is', 0);       #余额抵扣0不抵扣 1抵扣
        $use_integral_is = $request->param('use_integral_is', 0); #积分抵扣0不抵扣 1抵扣
        $card_goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,addtime,card_num')
            ->where(['id' => $card_id])
            ->where(['status' => 1])
            ->find();
        if (empty($card_goods)){
            return $this->renderError("盒子不存在或已下架");
        }
        //奖品信息
        $is_goodslist = GoodsList::field('id')
            ->where('goods_id', '=', $card_goods['id'])
            ->where('num', '=', 0)
            ->where('real_pro', '>', 0)
            ->where('special_stock', '<>', 0)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        //抽数设置
        $card_set = getConfig('card_set');
        if (!isset($card_set[$type])) {
            return $this->renderError("配置错误,请联系管理员");
        }
        $prize_card_set = NULL;
        if ($type == 'left_count') {
            $pre_type = 'left';
        } elseif ($type == 'center_count') {
            $pre_type = 'center';
        } elseif ($type == 'right_count') {
            $pre_type = 'right';
        } else {
            return $this->renderError("请求参数错误!!!");
        }
        // dd($type);
        $num = $card_set[$type] * $card_goods['card_num'];
        $key_shang_id = $pre_type . '_shang_id';
        // dd($key_shang_id);
        //查询出必出的卡等级
        if (isset($card_set[$key_shang_id])) {
            $prize_card_set = json_encode([
                'shang_id' => $card_set[$key_shang_id],
                'shang_count' => 1,
            ]);
        }else{
            $prize_card_set = null;
        }
        
        $goods_price = $card_goods['price'];
        
        //订单金额 微信支付金额
        $order_total = $order_zhe_total = $price = bcmul("$goods_price", "$num", 2);

        //潮币抵扣
        $use_integral = 0;
        if ($use_integral_is == 1) {
            if ($user['integral'] >= $price) {
                $use_integral = $price;
                $price = 0;
            } else {
                $use_integral = $user['integral'];
                $price = bcsub("$price", "{$user['integral']}", 2);
            }
        }
        //余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money'];#
                $price = bcsub("$price", "{$user['money']}", 2);
            }
        }
        //更新缓存
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "kpw_cardextractor_orderbuy" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 10);
        }
        //开启事务
        Db::startTrans();
        $order_num = create_order_no('MH_', 'order', 'order_num');
        
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id' => $user['id'],
            'order_num' => $order_num,
            'order_total' => $order_total,#订单金额
            'order_zhe_total' => $order_zhe_total,#订单折扣金额
            'price' => $price,#微信支付
            'use_money' => $use_money,#余额抵扣
            'use_integral' => $use_integral,#潮币抵扣
            'use_score' => 0,#积分抵扣
//            'zhe' => $zhe,#会员折扣
            'goods_id' => $card_id,
            'num' => 0,
            'goods_price' => $card_goods['price'],
            'goods_title' => $card_goods['title'],
            'goods_imgurl' => $card_goods['card_banner'],
            'prize_num' => $num,
            'prize_card_set' => $prize_card_set,
            'status' => 0,
            'pay_type' => 1,#1微信 2支付宝
            'order_type' => $card_goods['type'],
            'addtime' => time(),
        ]);
         
        //微信支付金额大于0
        if ($price > 0) {
            
            $body = '购买盒子' . $card_goods['title'];
            $attach = 'order_ckj';
            $payRes = (new Pay())->wxCreateOrder($order_num, $price, $user['openid'], $body, $attach);
            if ($payRes['status'] == 1) {
                #结果集
                $new_data = [
                    'status' => 1,
                    'order_num' => $order_num,
                    'res' => $payRes['data'],
                ];
            } else {
                #删除redis
                $redis->del($redis_key);
                Db::rollback();
                return $this->renderError("下单失败");
            }
        } else {
            #开盒子
            $res[] = (new Notify($this->app))->cardextractor_drawprize_notice($user['id'], $order_id, $card_id);
            // dd($res);
            #结果集
            $new_data = [
                'status' => 0,
                'order_num' => $order_num,
            ];
        }
        // dd(resCheck($res));
        if (!resCheck($res)) {
            Db::rollback();
            //删除redis
            // dd($redis_key);
            $redis->del($redis_key);
            // dd($redis->del($redis_key));
            return $this->renderError("购买失败,请刷新重试");
        }
        Db::commit();
        //删除redis
        $redis->del($redis_key);
        return $this->renderSuccess("下单成功", $new_data);
    }

    /**
     * 抽中的奖品
     * @param Request $request
     * created by Admin at 2022/12/9 15:07
     */
    public function prize_log(Request $request){
        $user = $this->getUser();
        $order_num = $request->param('order_num');
        $order_info = Order::where('order_num','=',$order_num)->find();
        if (empty($order_info)){
            return $this->renderError('订单不存在,请刷新后重试');
        }
        $data = OrderList::field('id,user_id,order_id,goodslist_title,goodslist_imgurl')
            // ->where('user_id',$user['id'])
            ->where('order_id',$order_info['id'])
            ->select();
        return $this->renderSuccess('操作成功',$data);
    }

    /**
     * 抽卡机规则
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/21 9:05
     */
    public function card_rule(){
        $info = Danye::where(['id' => 6])->find();
        if ($info) {
            $content = contentUrl($info['content']);
        } else {
            $content = '';
        }
        return $this->renderSuccess("请求成功", $content);
    }
}